﻿using System;
using System.Windows;
using System.Windows.Media.Imaging;
using QRCodeReader.Win32Api;

namespace QRCodeReader
{
    public class ScreenCapture
    {
        public static BitmapSource CaptureRegion(int x, int y, int width, int height)
        {
            return CaptureRegion(User32.GetDesktopWindow(), x, y, width, height);
        }

        public static BitmapSource CaptureRegion(
            IntPtr hWnd, int x, int y, int width, int height)
        {
            var sourceDC = IntPtr.Zero;
            var targetDC = IntPtr.Zero;
            var compatibleBitmapHandle = IntPtr.Zero;
            BitmapSource bitmap;

            try
            {
                sourceDC = User32.GetDC(User32.GetDesktopWindow());
                targetDC = Gdi32.CreateCompatibleDC(sourceDC);
                compatibleBitmapHandle = Gdi32.CreateCompatibleBitmap(sourceDC, width, height);
                
                Gdi32.SelectObject(targetDC, compatibleBitmapHandle);
                Gdi32.BitBlt(targetDC, 0, 0, width, height, sourceDC, x, y, Gdi32.SRCCOPY);
                
                bitmap = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                    compatibleBitmapHandle, IntPtr.Zero, Int32Rect.Empty,
                    BitmapSizeOptions.FromEmptyOptions());
            }
            catch (Exception ex)
            {
                throw new ScreenCaptureException(string.Format("Error capturing region {0},{1},{2},{3}", x, y, width, height), ex);
            }
            finally
            {
                Gdi32.DeleteObject(compatibleBitmapHandle);

                User32.ReleaseDC(IntPtr.Zero, sourceDC);
                User32.ReleaseDC(IntPtr.Zero, targetDC);
            }

            return bitmap;
        }
    }
}